<template>
  <div class="com-full">
    <Card :name="name">
      <template #body>
        <div class="com-full com-flex-r com-center">
          <div class="com-flex-1 com-flex-c com-center">
            <div class="left com-center">
              <Echart class="com-full" :options="option" />
            </div>
          </div>
          <div class="com-flex-1 right com-center">
            <comRecord :list="list" />
          </div>
        </div>
      </template>
    </Card>
  </div>
</template>

<script setup>
import Card from "@/components/Card/Card.vue";
import Echart from "@/components/Echarts/Echarts.vue";
import { circular_option } from "@/utils/options/DoughnutChart.option";
import comRecord from "../comRecord/comRecord.vue";
import { ref, computed, watch, onMounted, onUnmounted } from "vue";
import { useParamsStore } from "@/stores/params.js";
import api from "@/api";
import bus from "@/utils/bus.js";
import { getOpt } from "../../options/MockData";

const paramsStore = useParamsStore();
const param = computed(() => paramsStore.param);
const name = "冷量统计";
const option = ref({});
const list = ref([
  {
    name: "可用冷量",
    value: 0,
    color: "#44cd53",
  },
  {
    name: "已用冷量",
    value: 0,
    color: "#16d2f2",
  },
]);
let isMockData = false;
const dataInit = async () => {
  option.value = circular_option([0, 0]);
  if (isMockData) {
    const mockdata = await getOpt(param.value.ueId);
    let v2 =
      getRandon(mockdata["v3"]?.min, mockdata["v3"]?.max) -
      getRandon(mockdata["v4"]?.min, mockdata["v4"]?.max);
    list.value[0].value = getRandon(mockdata["v4"]?.min, mockdata["v4"]?.max);
    list.value[1].value = parseFloat(v2.toFixed(2));
    option.value = circular_option([list.value[0].value, list.value[1].value]);
  } else {
    try {
      const { data } = await api.cabinet(param.value);
      list.value[0].value = data?.availableCold ?? 0;
      list.value[1].value = data?.useCold ?? 0;
      option.value = circular_option([list.value[0].value, list.value[1].value]);
    } catch (error) {
      console.log(error);
    }
  }
};
//取随机数
const getRandon = (min, max) => {
  if (min === max) {
    return max;
  }
  if (min === 0 && max === 0) {
    return 0;
  }
  min = Math.ceil(min);
  max = Math.floor(max);
  const num = Math.floor(Math.random() * (max - min + 1)) + min;
  const randomDecimal = Math.random().toFixed(2).substring(1); // 生成0.xx格式的字符串，然后去掉前面的0
  return parseFloat(`${num}${randomDecimal}`);
};

onMounted(() => {
  bus.on("useMock", (e) => {
    isMockData = e;
    dataInit();
  });
});
onUnmounted(() => {
  bus.off("useMock", (e) => {
    isMockData = e;
    dataInit();
  });
});
watch(
  () => param.value,
  () => {
    dataInit();
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
.left {
  display: flex;
  width: 270px;
  height: 270px;
  background: url("/imgs/21.png");
  background-repeat: no-repeat;
  // background-size: 100% 100%;
}
</style>
